package com.wmlive.hhvideo.heihei.personal.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.wmlive.hhvideo.common.base.DcBaseActivity;
import com.wmlive.hhvideo.heihei.personal.widget.EnhanceSwipeRefreshLayout;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.RegexUtil;
import com.wmlive.hhvideo.utils.preferences.SPUtils;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by XueFei on 2017/6/05.
 * Modify by lsq
 * 支持隐式启动，启动的scheme="hhvideo",启动的intent-filter action{@link WebViewActivity#WEB_ACTION}
 * 支持显示纯html代码
 * 支持下拉刷新页面
 */

public class WebViewActivity extends DcBaseActivity implements
        EnhanceSwipeRefreshLayout.CanChildScrollUpCallback,
        SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.srlRoot)
    EnhanceSwipeRefreshLayout srlRoot;
    public static final String WEB_ACTION = "cn.wmlive.hhvideo.webpage";//隐式启动的action

    private WebView webView;
    private WebSettings mSettings;

    public static final String WEB_URL = "webUrl";//浏览的url
    public static final String WEB_TITLE = "WebTitle";//浏览的title，可选
    public static final String WEB_TAG = "WebTag";//浏览的tag，可选

    private String url;//浏览的url
    private String tag;//浏览的tag，可选，用于特殊的view操作
    private String title;//浏览的title，可选
    private Disposable disposable;

    public static void startWebActivity(Context context, String url, String title) {
        startWebActivity(context, null, url, title);
    }

    /**
     * @param context
     * @param tag
     * @param url
     * @param title
     */
    public static void startWebActivity(Context context, String tag, String url, String title) {
        startWebActivity(context, tag, url, title, null);
    }

    public static void startWebActivity(Context context, String tag, String url, String title, Bundle bundle) {
        startWebActivity(context, bundle, tag, url, title);
    }

    public static void startWebActivity(Context context, Bundle bundle, String tag, String url, String title, int... flags) {
        Bundle extras = (bundle == null) ? (new Bundle()) : bundle;
        extras.putString(WEB_TAG, tag);
        extras.putString(WEB_URL, url);
        extras.putString(WEB_TITLE, title);
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtras(extras);
        if (flags.length > 0) {
            for (int flag : flags) {
                intent.addFlags(flag);
            }
        }
        context.startActivity(intent);
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        if (intent != null) {
            Uri uri = intent.getData();
            if (null != uri) {//隐式启动
                url = uri.getQueryParameter("url");
            } else {//显式启动
                url = getIntent().getStringExtra(WEB_URL);
                title = getIntent().getStringExtra(WEB_TITLE);
                tag = getIntent().getStringExtra(WEB_TAG);
            }
            if (!TextUtils.isEmpty(url)) {
                setWebView();
            } else {
                toastFinish();
            }
        } else {
            toastFinish();
        }
    }

    private void setWebView() {
        setTitle(R.string.app_name, true);
        srlRoot.setColorSchemeResources(R.color.colorPrimary);
        srlRoot.setOnRefreshListener(this);
        srlRoot.setCanChildScrollUpCallback(this);
        webView = new WebView(this);
        webView.setWebViewClient(new MyWebViewClient());
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(layoutParams);
        webView.setWebChromeClient(mWebChromeClient);
        mSettings = webView.getSettings();
        String defaultUA = mSettings.getUserAgentString();
        mSettings.setUserAgentString(defaultUA);
//            mSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mSettings.setUseWideViewPort(true);
        mSettings.setDomStorageEnabled(true);
        mSettings.setLoadWithOverviewMode(true);
        // 设置可以支持缩放
        mSettings.setSupportZoom(true);
        // 设置出现缩放工具
        mSettings.setBuiltInZoomControls(true);
        // 自适应屏幕
        mSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.setBackgroundColor(getResources().getColor(R.color.transparent));
        webView.getSettings().setSavePassword(false);
        // 同步cookie
        synCookies();
        srlRoot.addView(webView, 0);
        loadWebPage(url);
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (null != srlRoot) {
                if (newProgress > 90) {
                    srlRoot.setRefreshing(false);
                } else {
                    if (!srlRoot.isRefreshing()) {
                        srlRoot.setRefreshing(true);
                    }
                }
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            onPageReceivedTitle(view, title);
        }
    };

    protected void onPageReceivedTitle(WebView view, String title) {
        KLog.e("------title:" + title);
        if (!TextUtils.isEmpty(title)) {
            setTitle(title, true);
        } else {
            if (TextUtils.isEmpty(title) || !RegexUtil.isContainsChineseChar(title)) {
                setTitle(R.string.app_name, true);
            } else {
                setTitle(title, true);
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null && mSettings != null) {
            mSettings.setJavaScriptEnabled(true);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null && mSettings != null) {
            mSettings.setJavaScriptEnabled(false);
        }
    }

    @Override
    public void onRefresh() {
        loadWebPage(webView.getUrl());
    }

    @Override
    public boolean canSwipeRefreshChildScrollUp() {
        return webView.getScrollY() > 0;
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url2) {
            loadWebPage(url2);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

    }

    private void loadWebPage(String url) {
        if (RegexUtil.isUrl(url)) {
            webView.loadUrl(url);
        } else {
            webView.loadDataWithBaseURL(null, url, "text/html", "UTF-8", null);
        }
    }

    /**
     * 同步一下cookie
     */
    private void synCookies() {

        // 移除
//先取从请求中获取的cookies
//设置cookie
//一个url的多个cookie，要调用多次setCookie
//        if (!cookies.isEmpty()) {
//            String[] cookieArray = cookies.split(";");
//            for (int i = 0; i < cookieArray.length; i++) {  // cookieArray是多个cookie的数组变量
//                cookieManager.setCookie(BasePresent.MAIN_HOST, cookieArray[i]);
//            }
//        }
//        //添加约定好的cookies 第一个参数是你访问的网址，不是cookie存储的域名
//        String imei = SPUtils.getString(this, "imei", "");
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Ap=heihei");
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Version=" + AppLogic.VERSION);
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Buildnumber=" + AppLogic.BUILD_NUMBER);
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Local=zh_CN");
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Uuid=" + (imei.isEmpty() ? AppLogic.getmPhoneInfo().mIMEI : imei));
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Model=" + AppLogic.getmPhoneInfo().mManufacturerName + ":" + AppLogic.getmPhoneInfo().mModelName);
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Resolution=" + AppLogic.getmPhoneInfo().mPhoneDeviceScreen);//分辨率
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "OsVersion=" + AppLogic.getmPhoneInfo().mSysVersion2);//系统版本
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "DeveiceType=android");
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Channel=" + AppLogic.CHANNEL);
        disposable = Observable.just(1)
                .subscribeOn(Schedulers.newThread())
                .map(new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer) throws Exception {
                        CookieSyncManager.createInstance(WebViewActivity.this);
                        CookieManager cookieManager = CookieManager.getInstance();
                        cookieManager.setAcceptCookie(true);
                        cookieManager.removeSessionCookie();// 移除
                        cookieManager.removeAllCookie();
                        //先取从请求中获取的cookies
                        String cookies = SPUtils.getString(WebViewActivity.this, SPUtils.COOKIES, "");
                        //设置cookie
                        //一个url的多个cookie，要调用多次setCookie
//        if (!cookies.isEmpty()) {
//            String[] cookieArray = cookies.split(";");
//            for (int i = 0; i < cookieArray.length; i++) {  // cookieArray是多个cookie的数组变量
//                cookieManager.setCookie(BasePresent.MAIN_HOST, cookieArray[i]);
//            }
//        }
//        //添加约定好的cookies 第一个参数是你访问的网址，不是cookie存储的域名
//        String imei = SPUtils.getString(this, "imei", "");
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Ap=heihei");
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Version=" + AppLogic.VERSION);
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Buildnumber=" + AppLogic.BUILD_NUMBER);
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Local=zh_CN");
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Uuid=" + (imei.isEmpty() ? AppLogic.getmPhoneInfo().mIMEI : imei));
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Model=" + AppLogic.getmPhoneInfo().mManufacturerName + ":" + AppLogic.getmPhoneInfo().mModelName);
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Resolution=" + AppLogic.getmPhoneInfo().mPhoneDeviceScreen);//分辨率
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "OsVersion=" + AppLogic.getmPhoneInfo().mSysVersion2);//系统版本
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "DeveiceType=android");
//        cookieManager.setCookie(BasePresent.MAIN_HOST, "Channel=" + AppLogic.CHANNEL);
                        CookieSyncManager.getInstance().sync();
                        return 1;
                    }
                })
                .subscribe();
    }

    @Override
    protected void onSingleClick(View v) {
        if (v.getId() == R.id.ivBack) {
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                finish();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (null != webView) {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        if (null != disposable && !disposable.isDisposed()) {
            disposable.dispose();
        }
        try {
            if (webView != null) {
                webView.stopLoading();
                webView.removeAllViews();
                webView.setVisibility(View.GONE);
                if (null != srlRoot && srlRoot.getChildCount() > 0) {
                    srlRoot.removeViewAt(0);
                }
                webView.destroy();
                webView = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            super.onDestroy();
        }
    }
}
